﻿$(document).ready(function () {
    $(".calendar-date").datepicker();
});

// First: Create config
ko.validation.configure({
    registerExtenders: true,
    messagesOnModified: true,
    insertMessages: true,
    parseInputAttributes: true,
    messageTemplate: null,
    decorateElement: true,
    errorClass: "error",
    errorMessageClass: "error-desc"
});

// Second: Create new model to apply to view
var viewModel = new function () {
    // About you
    this.Title = ko.observable(data.ProductInfo.Title).extend({ maxLength: 250 }).extend({ required: { message: "Tiêu đề bản tin là bắt buộc"} });
    this.ShortDesc = ko.observable(data.ProductInfo.ShortDesc);
    this.LongDesc = ko.observable(data.ProductInfo.LongDesc);
    this.ImageUrl = ko.observable("/Upload/Product/" + data.ProductInfo.ImageURL);
    this.FileName = ko.observable(data.ProductInfo.ImageURL);
    this.Active = ko.observable(true);
    this.AcceptPayment = ko.observable(false);

    // Categories
    this.AllCategories = ko.observable(data.ProductInfo.ShowAllCategories);
    this.CategoryList = ko.observableArray(data.ListCategory);
    this.CategoryID = ko.observable(data.ProductInfo.CategoryID);
    this.SubCategoryOptionList = ko.observableArray(data.ListSubCategory);
    this.SubCategoryList = ko.computed(function () {
        var cate = this.CategoryID();
        return ko.utils.arrayFilter(this.SubCategoryOptionList(), function (option) {
            return option.ParentID == cate;
        });
    }, this);
    this.SubSelectedID = ko.observable(data.ProductInfo.SubCategoryID);

    // Submit, Next button
    this.InvalidateForm = ko.observable(false);
    this.SubmitForm = function () {
        if (viewModel.errors().length == 0) {
            $('form').submit();
        }
        else {
            viewModel.errors.showAllMessages();
            this.InvalidateForm(true);
        }
    }
};

viewModel.errors = ko.validation.group(viewModel);

// Third: Apply view model to view to handle action when user input data
ko.validation.rules.pattern.message = 'Invalid.';
ko.applyBindings(viewModel, document.getElementById("main"));
